package com.itheima.mm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mm.dto.R;
import com.itheima.mm.pojo.subject_manage.Directorys;
import com.itheima.mm.pojo.PageResult;
import com.itheima.mm.service.DirectorysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/directorys")
public class DirectorysController {
    @Autowired
    private DirectorysService directorysService;

    //目录修改
    @PutMapping("/{id}")
    public R modify(@PathVariable Integer id, @RequestBody Directorys directorys){
        directorysService.updateById(directorys);
        R r=new R();
        r.setSuccess(true);
        return r;
    }

    //目录列表
    @GetMapping
    public PageResult page(String directoryName,Integer state,Integer page,Integer pagesize){
        LambdaQueryWrapper<Directorys> wrapper=new LambdaQueryWrapper<>();
        if (directoryName!=null)
            wrapper.like(Directorys::getDirectoryName,directoryName);
        if (state!=null)
            wrapper.eq(Directorys::getState,state);
        IPage<Directorys> p=new Page<>(page,pagesize);
        IPage<Directorys> pg = directorysService.page(p, wrapper);
        return new PageResult(pg.getTotal(),pg.getSize(),pg.getPages(),pg.getCurrent(),pg.getRecords());
    }

    //目录删除
    @DeleteMapping("/{id}")
    public R del(@PathVariable Integer id){
        directorysService.removeById(id);
        R r=new R();
        r.setSuccess(true);
        return r;
    }

    //目录添加
    @PostMapping
    public R add(@RequestBody Directorys directorys){
        directorys.setSubjectId(1);
        directorys.setCreatorId(1);
        directorys.setTotals(1);
        directorys.setAddDate(LocalDateTime.now());
        directorysService.save(directorys);
        LambdaQueryWrapper<Directorys> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Directorys::getDirectoryName,directorys.getDirectoryName());
        Directorys one = directorysService.getOne(wrapper);
        R r=new R();
        r.setId(one.getId());
        return r;
    }

    //目录状态
    @PostMapping("/{id}/{state}")
    public R DirectoryState(@PathVariable Integer id,@PathVariable Integer state){
        Directorys directorys=new Directorys();
        directorys.setId(id);
        directorys.setState(state);
        directorysService.updateById(directorys);
        R r=new R();
        r.setSuccess(true);
        return r;
    }

    //目录详情
    @GetMapping("/{id}")
    public Directorys findById(@PathVariable Integer id){
        Directorys byId = directorysService.getById(id);
        return byId;
    }
}
